<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:activity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:activity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:activity:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:activity:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动标题" align="center" prop="activityTitle" />
      <el-table-column label="活动开始时间" align="center" prop="activityStartTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="activityEndTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" width="80" prop="coverImgUrl" >
        <template scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="baseUrl + scope.row.coverImgUrl" style="height: 400px;width: 500px">
            <img slot="reference" :src="baseUrl + scope.row.coverImgUrl" :alt="baseUrl + scope.row.coverImgUrl" style="max-height: 50px;max-width: 130px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1 || scope.row.status == 4"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleStatus(scope.row, '2')"
            v-hasPermi="['app:activity:edit']"
          >启动</el-button>
          <el-button
            v-if="scope.row.status == 2"
            size="mini"
            type="text"
            icon="el-icon-video-pause"
            @click="handleStatus(scope.row, '4')"
            v-hasPermi="['app:activity:edit']"
          >暂停</el-button>
          <el-button
            v-if="scope.row.status == 1 || scope.row.status == 4"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:activity:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status == 2 || scope.row.status == 4"
            size="mini"
            type="text"
            icon="el-icon-switch-button"
            @click="handleStatus(scope.row, '3')"
            v-hasPermi="['app:activity:edit']"
          >停止</el-button>
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:activity:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改APP活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="活动标题" prop="activityTitle">
          <el-input v-model="form.activityTitle" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动开始时间" prop="activityStartTime">
          <el-date-picker clearable size="small"
                          v-model="form.activityStartTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="activityEndTime">
          <el-date-picker clearable size="small"
                          v-model="form.activityEndTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择活动结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :show-file-list="false"
            :headers="upload.headers"
            name="file"
            accept=".jpg, .png"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动内容">
<!--          <editor v-model="form.activityContent" :min-height="192"/>-->
          <Tinymce v-if="open" v-model="form.activityContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
import { getToken } from "@/utils/auth";
import { listActivity, getActivity, updateStatus, delActivity, addActivity, updateActivity, exportActivity } from "@/api/app/activity";
import Editor from '@/components/Editor';
import Tinymce from '@/components/Tinymce';

export default {
  name: "Activity",
  components: {
    Editor,
    Tinymce
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // baseUrl: process.env.VUE_APP_BASE_API,
      baseUrl: "https://youhuiniu.oss-cn-beijing.aliyuncs.com/",
      imageUrl: '',
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        // 上传的文件列表
        fileList: []
      },
      // 总条数
      total: 0,
      // APP活动表格数据
      activityList: [],
      // 活动状态字典
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityTitle: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityTitle: [
          { required: true, message: "活动标题不能为空", trigger: "blur" }
        ],
        coverImgUrl: [
          { required: true, message: "封面图片URL不能为空", trigger: "blur" }
        ],
        activityContent: [
          { required: true, message: "活动内容不能为空", trigger: "blur" }
        ],
        activityStartTime: [
          { required: true, message: "活动开始时间不能为空", trigger: "blur" }
        ],
        activityEndTime: [
          { required: true, message: "活动结束时间不能为空", trigger: "blur" }
        ],
        Tinymceas:true
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("app_activity_state").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询APP活动列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 活动状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityTitle: null,
        coverImgUrl: null,
        coverImgUrl2: null,
        activityContent: null,
        activityStartTime: null,
        activityEndTime: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.imageUrl = '';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加APP活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {

      this.reset();
      const activityId = row.activityId || this.ids
      getActivity(activityId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改APP活动";
        this.imageUrl = this.baseUrl + this.form.coverImgUrl;
      });
    },
    /** 启动/暂停/停止按钮操作 */
    handleStatus(row, status) {
      const statusStr = status == 4 ? "暂停" : (status == 2 ? "启动" : (status == 3 ? "停止" : ""))
      const activityId = row.activityId || this.ids
      this.$confirm('是否' + statusStr + '活动?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return updateStatus(activityId, status);
      }).then(() => {
        this.getList();
        this.msgSuccess(statusStr + "成功");
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.activityId != null) {
            updateActivity(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivity(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const activityIds = row.activityId || this.ids;
      this.$confirm('是否确认删除该APP活动?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActivity(activityIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有APP活动数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportActivity(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleAvatarSuccess(res, file) {
      this.form.coverImgUrl = res.data.objectID;;
      this.imageUrl = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
  }
};
</script>
